package tlcn.app;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import tlcn.business.ListDateShopAdapter;
import tlcn.business.ManagerData;
import tlcn.data.Material;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

public class ShoppingActivity extends Activity{
	ListDateShopAdapter adapter;
	String where;
	ArrayList<String> listDate;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.acticity_shopping);
		listDate = getListDate();
		adapter= new ListDateShopAdapter(getApplicationContext(),R.layout.item_date, listDate);
		ListView ltvDateOfShop= (ListView) findViewById(R.id.ltvDateShop);
		ltvDateOfShop.setAdapter(adapter);
		Button btnShop=(Button) findViewById(R.id.btnShop);
		btnShop.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				where="";
				for(int i=0;i<adapter.listCheck.size();i++)
					if(adapter.listCheck.get(i))
					{
						String strArrtmp[]=(listDate.get(i)).split("/");
						int da=Integer.parseInt(strArrtmp[0]);
						int mo=Integer.parseInt(strArrtmp[1]);
						int ye=Integer.parseInt(strArrtmp[2]);
						where=where+"OR Date='"+ye+"-"+mo+"-"+da+"'";
					}
				if(where!="")
				{
					where=where.substring(2);
					ArrayList<Material> materials=new ManagerData(getApplicationContext()).getShopping(where);
					String[] items= new String[materials.size()];
					for (int i=0;i<materials.size();i++) {
						//Log.d("test",m.getWeight()+" "+m.getMaterialName());
						items[i]=(materials.get(i).getWeight()+" "+materials.get(i).getMaterialName()+"\n");
					}
					Builder builder=new Builder(ShoppingActivity.this);
					builder.setTitle("Shopping");
					builder.setItems(items, null);
					builder.setPositiveButton("OK",null);
					AlertDialog dialog = builder.create();
					dialog.show();
				}
			}
		});
	}
	private ArrayList<String> getListDate(){
		ArrayList<String> list = new ArrayList<String>();
		Calendar ca= Calendar.getInstance();
		SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault());
		String s=sdf.format(ca.getTime());
		String strArrtmp[]=s.split("/");
		int da=Integer.parseInt(strArrtmp[0])-1;
		int mo=Integer.parseInt(strArrtmp[1]);
		int ye=Integer.parseInt(strArrtmp[2]);
		int max=30;
		if(mo==1||mo==3||mo==5||mo==7||mo==8||mo==10||mo==12)
			max=31;
		else if (mo==2){
			if ((ye%4==0&&ye%100!=0)||(ye%400==0))
				max=29;
			else max=28;
		}
		for (int i=0;i<14;i++){
			if (da==max)	{
				da=1;
				if(mo==12){mo=1;ye++;}
				else mo++;
			}else da++;
			list.add(da+"/"+mo+"/"+ye);
		}
		return list;
	}

}
